package cn.topevery.garden.dal.dao.impl;

import cn.topevery.garden.dal.dao.DeviceObjectRelateDao;
import cn.topevery.garden.dal.util.DurationUtil;
import cn.topevery.garden.dal.util.GeomHelper;
import cn.topevery.garden.entity.po.DeviceObjectRelate;
import cn.topevery.garden.entity.po.GpsClientState;
import cn.topevery.garden.entity.po.GpsPosTraceLocal;
import cn.topevery.garden.entity.query.DeviceObjectRelateQuery;
import cn.topevery.garden.entity.query.DeviceObjectResultQuery;
import cn.topevery.garden.entity.vo.DeviceObjectResultVO;
import cn.topevery.garden.framework.base.BaseDaoImpl;
import hw.topevery.framework.db.CommandType;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.db.entity.SqlQueryMate;
import hw.topevery.framework.db.enums.ScriptConditionEnum;
import hw.topevery.framework.entity.DbCsp;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 The type Device object relate dao.
 *
 * @author code -generate
 * @created 2021 -09-08 14:54:19
 * @date 2021 -09-08
 */
@Repository
public class DeviceObjectRelateDaoImpl extends BaseDaoImpl<DeviceObjectRelate> implements DeviceObjectRelateDao {
    /**
     * 描述 Gets search.
     *
     * @param <P>  the type parameter
     * @param para the para
     * @return the search
     * @author wenzhao.lin
     * @created 2021 -09-08 14:54:19
     */
    @Override
    public <P extends DbCsp> List<DeviceObjectRelate> getSearch(P para) {
        return null;
    }


    /**
     * 描述 分页列表.
     *
     * @param query the query
     * @return the data pager
     * @author wenzhao.lin
     * @created 2021 -09-08 14:05:44 List page data pager.
     */
    @Override
    public DataPager<DeviceObjectRelate> listPage(DeviceObjectRelateQuery query) {
        String table = "t_device_object_relate tdor";

        String columns = "tdor.*";

        int pageIndex = query.pageIndex - 1;
        int pageSize = query.pageSize;

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns).setOrderBy("tdor.c_id desc");
        sqlQueryMate
                .where(true, "tdor.c_db_status", ScriptConditionEnum.Eq, 0)
        ;

        return getDataPager(sqlQueryMate, pageSize, pageIndex, DeviceObjectRelate.class);
    }

    /**
     * 描述 所有数据列表
     *
     * @param type the type
     * @return the all list
     * @author wenzhao.lin
     * @created 2021 -09-08 14:05:39
     */
    @Override
    public List<DeviceObjectRelate> getAllList(Integer type) {
        String table = "t_device_object_relate tdor " +
                "inner join t_person p on p.c_id = tdor.c_object_id";

        String columns = "tdor.*";

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns);
        sqlQueryMate
                .where(true, "tdor.c_db_status", ScriptConditionEnum.Eq, 0)
                .where(true, "p.c_db_status", ScriptConditionEnum.Eq, 0)
                .where(type != null, "tdor.c_object_type", ScriptConditionEnum.Eq, type)
        ;

        return selectList(sqlQueryMate, DeviceObjectRelate.class);
    }

    private HashMap<Integer,String> deviceTypeMapper= new HashMap() {
        {
            put(3,"4ccc6c9a-80ae-4c03-be6d-23b22e13bb09");
            put(7,"d408daf6-1fc9-49a8-9927-ba53ff07a9f3");
            put(8,"23ace7c4-9123-44cf-91a1-7e546c5ea2f9");
            put(11,"7fbc583f-ee89-4e64-87d9-00e048581dab");
            put(12,"607f2817-192c-4630-be88-ec1d503d700e");
            put(13,"1cacd297-4f16-49fd-85e1-07d1d1959ce0");
        }
    };

    /**
     * 描述 获取数据列表
     *
     * @param query the query
     * @return the person page
     * @author wenzhao.lin
     * @created 2021 -09-08 14:54:20
     */
    @Override
    public DataPager<DeviceObjectResultVO> getDataPage(DeviceObjectResultQuery query) {
        String table = "";
        String columns = "";

        // type:0-人员列表，1-车辆列表
        if (query.getType() == 0) {
            table = "t_person p " +
                    "left join t_device_object_relate dt on p.c_id = dt.c_object_id and dt.c_object_type=0 " +
                    "left join t_gps_device g on g.c_id = dt.c_device_id ";

            columns = "p.c_id c_object_id,p.c_user_id as c_data_id,p.c_name,p.c_type_name, g.*";

        } else if (query.getType() == 1) {
            table = "t_car p " +
                    "left join t_device_object_relate dt on p.c_id = dt.c_object_id  and dt.c_object_type=1 " +
                    "left join t_gps_device g on g.c_id = dt.c_device_id";

            columns = "p.c_id c_object_id,p.c_car_num c_name,p.c_type_name, g.*";
        } else {
            table = "t_facilities p " +
                    "left join t_device_object_relate dt on p.c_id = dt.c_object_id and dt.c_object_type="+query.getType()+" "+
                    "left join t_gps_device g on g.c_id = dt.c_device_id ";

            columns = "p.c_id c_object_id,p.c_name,p.c_type_name, g.*";
        }

        int pageIndex = query.pageIndex - 1;
        int pageSize = query.pageSize;



        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns).setOrderBy("dt.c_code desc");
        sqlQueryMate
                .where(true, "p.c_db_status", ScriptConditionEnum.Eq, 0)
                .where(StringUtils.isNotEmpty(query.getCode()), "dt.c_code", ScriptConditionEnum.Eq, query.getCode())
                .where(StringUtils.isNotEmpty(query.getName()) && query.getType().equals(0), "p.c_name", ScriptConditionEnum.Like, query.getName())
                .where(StringUtils.isNotEmpty(query.getName()) && query.getType().equals(1), "p.c_car_num", ScriptConditionEnum.Like, query.getName())
//                .where(query.getType()>1, "dt.c_object_type", ScriptConditionEnum.Eq, query.getType())
                .where(query.getType()>1, "p.c_type_id", ScriptConditionEnum.Eq, deviceTypeMapper.get(query.getType()))
//                .where(query.getType()>1, "p.c_type_name", ScriptConditionEnum.Like, query.getTypeName())
        ;

        return getDataPager(sqlQueryMate, pageSize, pageIndex, DeviceObjectResultVO.class);
    }

    /**
     * 描述 检查是否已经存在.
     *
     * @param fieldName 字段名
     * @param value     字段值
     * @return the boolean （true已存在，false不存在）
     * @author wenzhao.lin
     * @created 2021 -08-19 09:23:47 Is exit boolean.
     */
    @Override
    public boolean isExit(String fieldName, String value, String ObjectType) {
        String table = "t_device_object_relate";
        String columns = fieldName;
        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns);
        sqlQueryMate
                .where(true, "c_db_status", ScriptConditionEnum.Eq, 0)
                .where(true, fieldName, ScriptConditionEnum.Eq, value)
                .where(StringUtils.isNotBlank(ObjectType), "c_object_type", ScriptConditionEnum.Eq, ObjectType)
        ;
        List<DeviceObjectRelate> list = selectList(sqlQueryMate, DeviceObjectRelate.class);
        if (list != null && list.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 描述 删除.
     *
     * @param deviceId the device id
     * @param objectId the object id
     * @author wenzhao.lin
     * @created 2021 -09-08 17:41:28 Delete by id.
     */
    @Override
    public void deleteById(Integer deviceId, Integer objectId) {
        String sql = "delete from t_device_object_relate where c_device_id = " + deviceId + " and c_object_id=" + objectId;
        run(sql, CommandType.Text, dbCommand -> {
            dbCommand.executeNonQuery();
        });
    }

    @Override
    public void currRelationToLocal(){
        run("p_local_client_key_update", CommandType.StoredProcedure, dbCommand -> {
            dbCommand.executeNonQuery();
        });
    }

    public void updatePosIns(){

        Map<String, Object> oneMap = getOneMap("select c_data_fid num from t_gre_local_new.t_gps_for_task");

        String table = "t_gre_local_new.t_gps_pos_trace_local tgptl";

        String columns = "tgptl.*";

        Long max = Long.parseLong(oneMap.get("num").toString())+2048;

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns);
        sqlQueryMate
                .where(true, "tgptl.c_gid", ScriptConditionEnum.GreaterThan, oneMap.get("num").toString())
                .where(true, "tgptl.c_gid", ScriptConditionEnum.LessThanEq, max)
        ;
        List<GpsPosTraceLocal> list = selectList(sqlQueryMate, GpsPosTraceLocal.class);

            for (GpsPosTraceLocal value:list) {

                Map<String, Object> csVal = getOneMap("select c_obj_type objectType,c_obj_id objectId from t_gre_local_new.t_gps_device_src where c_client_key ="+value.clientKey);

                run("p_gps_pos_ins_v2", CommandType.StoredProcedure, dbCmd -> {
                    dbCmd.addInParameter("pi_fid", value.fid);
                    dbCmd.addInParameter("pi_client_key", value.clientKey);
                    dbCmd.addInParameter("pi_client_ip", value.clientIp);
                    dbCmd.addInParameter("pi_client_port", value.clientIpPort);
                    dbCmd.addInParameter("pi_speed", value.speed);
                    dbCmd.addInParameter("pi_degree", value.degree);
                    dbCmd.addInParameter("pi_star_number", value.starNumber);
                    dbCmd.addInParameter("pi_long", value.lng);
                    dbCmd.addInParameter("pi_lat", value.lat);
                    dbCmd.addInParameter("pi_abs_y", value.absY);
                    dbCmd.addInParameter("pi_abs_x", value.absX);
                    dbCmd.addInParameter("pi_gps_device_date", value.gpsDate);
                    dbCmd.addInParameter("pi_gps_date", value.gpsDate);
                    dbCmd.addInParameter("pi_db_create_date", value.createTime);
                    dbCmd.addInParameter("pi_gsm_signal_intensity", value.gsmSignalIntensity);
                    dbCmd.addInParameter("pi_state", value.state);
                    dbCmd.addInParameter("pi_up_model", value.upModel);
                    dbCmd.addInParameter("pi_up_type", value.upType);
                    dbCmd.addInParameter("pi_obj_type", csVal != null ?csVal.get("objectType").toString() : null);
                    dbCmd.addInParameter("pi_obj_id", csVal != null ? csVal.get("objectId").toString() : null);
                    dbCmd.addInParameter("pi_avg2_speed", getSpeedAvg2(value.absX,value.absY,value.gpsDate, value.clientKey));

                    dbCmd.executeNonQuery();
                });

            }

    }

    public void updateStateIns(){

        Map<String, Object> oneMap = getOneMap("select c_data_fid num from t_gre_local_new.t_gps_for_task");

        String table = "t_gre_local_new.t_gps_client_state tgptl";

        String columns = "tgptl.*";

        Long max = Long.parseLong(oneMap.get("num").toString())+2048;

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns);
        sqlQueryMate
                .where(true, "tgptl.c_gid", ScriptConditionEnum.GreaterThan, oneMap.get("num").toString())
                .where(true, "tgptl.c_gid", ScriptConditionEnum.LessThanEq, max)
        ;
        List<GpsClientState> list = selectList(sqlQueryMate, GpsClientState.class);
            for (GpsClientState value:list) {

                Map<String, Object> csVal = getOneMap("select c_obj_type objectType,c_obj_id objectId from t_gre_local_new.t_gps_device_src where c_client_key ="+value.clientKey);

                run("p_gps_client_state_ins", CommandType.StoredProcedure, dbCmd -> {
                    dbCmd.addInParameter("pi_fid", value.fid);
                    dbCmd.addInParameter("pi_data_source", null);
                    dbCmd.addInParameter("pi_client_key", value.clientKey);
                    dbCmd.addInParameter("pi_client_ip", value.clientIp);
                    dbCmd.addInParameter("pi_client_port", value.clientIpPort);
                    dbCmd.addInParameter("pi_db_create_date", value.createTime);
                    dbCmd.addInParameter("pi_acc_state", value.accState ? 1 : 0);
                    dbCmd.addInParameter("pi_charge_state", value.chargeState ? 1 : 0);
                    dbCmd.addInParameter("pi_client_info", value.clientInfo);
                    dbCmd.addInParameter("pi_defend_state", value.defendState ? 1 : 0);
                    dbCmd.addInParameter("pi_gps_state", value.gpsState ? 1 : 0);
                    dbCmd.addInParameter("pi_language", value.language);
                    dbCmd.addInParameter("pi_oli_telegram_state", value.oliTelegramState ? 1 : 0);
                    dbCmd.addInParameter("pi_voltage_level", value.voltageLevel);
                    dbCmd.addInParameter("pi_warning_ext_info", value.warningExtInfo);
                    dbCmd.addInParameter("pi_warning_state", value.warningState);
                    dbCmd.addInParameter("pi_warning_ext_info_child_0", value.warningExtInfoChild0);
                    dbCmd.addInParameter("pi_obj_type", csVal != null ?csVal.get("objectType").toString() : null);
                    dbCmd.addInParameter("pi_obj_id", csVal != null ? csVal.get("objectId").toString() : null);
                    dbCmd.executeNonQuery();
                });

            }


        }



    public void updateTask(){

        Map<String, Object> oneMap = getOneMap("select max(c_gid) num from t_gre_local_new.t_gps_client_state");
        Long max = Long.parseLong(oneMap.get("num").toString());

        String sql = "update t_gre_local_new.t_gps_for_task set c_data_fid="+max+", c_exec_date= '" + LocalDateTime.now()+"'";
            run(sql, CommandType.Text, dbCommand -> {
                dbCommand.executeNonQuery();
            });

    }


    public double getSpeedAvg2(double absX,double absY,LocalDateTime gpsDate,String clientKey) {
        double speedAvg2 = 1;

        Map<String, Object> speed = getOneMap("select c_abs_x absX,c_abs_y absY,c_gps_date gpsDate " +
                "from t_gre_local_new.t_gps_pos_trace_local where c_client_key ="+clientKey+" order by c_fid desc limit 1");

        double preDateSeconds = Math.abs(DurationUtil.subtractSeconds(gpsDate, (LocalDateTime) speed.get("gpsDate")));
        if (0 < preDateSeconds && preDateSeconds < 10 * 60) {
            speedAvg2 = GeomHelper.getPointDistance(absX,  (double) speed.get("absX"), absY, (double)  speed.get("absY")) / preDateSeconds;
        }
        return speedAvg2;
    }


}
